package oojo.data.impl.exec.sub;

import javax.persistence.EntityManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import oojo.data.Query;
import oojo.data.QueryException;
import oojo.data.spec.sub.SubCreate;
import oojo.data.impl.SubRepositoryImpl;
import oojo.data.impl.exec.CreateQuery;

public class SubCreateQuery<E> extends CreateQuery<E> {

    private static final Logger logger = LoggerFactory.getLogger(SubCreateQuery.class);
    
    public Class<?> getQueryClass() {
        return SubCreate.class;
    }
    
    public E execute(Query<E, E> create) {
        logger.debug("---> execute(spec)");
        
        try {
            SubCreate<E> spec = (SubCreate<E>) create;
            
            if (spec.getParentId() != null) {
                SubRepositoryImpl<E> repository = (SubRepositoryImpl<E>) getRepository();
                EntityManager entityManager = getRepository().getEntityManager();
                Object parent = entityManager.find(repository.getParentClass(), spec.getParentId());
                repository.link(parent, spec.getEntity());
            }
            
            return super.execute(create);
        } catch (Exception ex) {
            throw new QueryException(ex);
        }
    }
}
